<template>
    <div class="app-container">
        <el-card shadow="never" v-loading="loading">
            <el-tabs v-model="searchForm.status" @tab-click="handleSearch">
                <el-tab-pane label="全部" :name="''"></el-tab-pane>
                <el-tab-pane label="未审核" :name="'未审核'"></el-tab-pane>
                <el-tab-pane label="审核中" :name="'审核中'"></el-tab-pane>
                <el-tab-pane label="已审核" :name="'已审核'"></el-tab-pane>
            </el-tabs>
            <el-row :gutter="5">
                <el-col :span="24" class="main-card-view">
                    <el-row>
                        <el-card shadow="never" class="top-search-view-card">
                            <el-row>
                                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                                    <el-form-item label="关键字搜索">
                                        <el-input v-model="searchForm.keyWork" placeholder="请输入"></el-input>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="handleSearch" class="search-button">查询
                                        </el-button>
                                        <!--                                        <el-button type="success" @click="handleReset" class="reset-button">重置</el-button>-->
                                        <el-button type="primary" @click="showCreateDialog" class="new-button">发布
                                        </el-button>
                                        <el-button @click="batchDel" class="del-button">批量删除
                                        </el-button>
                                    </el-form-item>
                                </el-form>
                            </el-row>
                        </el-card>
                    </el-row>

                    <el-row>
                        <el-card shadow="never">
                            <el-table :data="tableData" :stripe="true" style="width: 100%"
                                @selection-change="handleSelection">
                                <el-table-column type="selection" width="55" :selectable="isSelectable">
                                </el-table-column>
                                <el-table-column prop="titleName" label="标题" width="400" />
                                <el-table-column prop="origin" align="center" label="来源" />
                                <el-table-column prop="publisher" align="center" label="发布人" />
                                <el-table-column prop="pageViewNum" align="center" label="浏览量" />
                                <el-table-column prop="status" align="center" label="状态" />
                                <!-- <el-table-column prop="collectNum" align="center" label="收藏量" />
                                 <el-table-column prop="sharenum" align="center" label="分享量" />
                                <el-table-column prop="reviewNum" align="center" label="评论量" /> -->
                                <el-table-column prop="createTime" align="center" label="创建时间" />
                                <el-table-column align="center" label="操作" width="200">
                                    <template slot-scope="scope">
                                        <el-button type="text" class="table-details-btn"
                                            @click="handleDetails(scope.$index, scope.row)"></el-button><!--详情-->
                                        <el-button type="text" class="table-edit-btn"
                                            v-if="scope.row.status === '未审核' || userInfo.roleName === '管理员'"
                                            @click="showEditDialog(scope.$index, scope.row)"></el-button>
                                        <!--编辑-->
                                        <el-button type="text" class="table-delete-btn" v-if="isSelectable(scope.row)"
                                            @click="handleDelete(scope.$index, scope.row)"></el-button><!--删除-->
                                    </template>
                                </el-table-column>
                            </el-table>
                            <XPagination ref="pageInfo" :total="total" :get-data="getList" />
                        </el-card>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog width="80%" :title="dialogTitle" :visible.sync="dialogVisible">
            <el-form label-width="120px" ref="form" :rules="formRules" :model="form">
                <el-form-item label="分类" prop="classify">
                    <el-cascader v-model="form.classifyUid" :options="options" :props="props" placeholder="请选择"
                        @change="handleChange" ref="cascader" style="width: 100%;"></el-cascader>
                </el-form-item>
                <el-form-item label="标题" prop="titleName">
                    <el-input v-model="form.titleName" />
                </el-form-item>
                <!-- <el-form-item label="副标题" prop="subtitle">
                    <el-input v-model="form.subtitle"/>
                </el-form-item> -->
                <el-form-item label="关键字" prop="keyWork">
                    <el-input v-model="form.keyWork" />
                </el-form-item>
                <el-form-item label="封面" prop="coverFileName">
                    <x-upload v-model="form.coverFileName" />
                </el-form-item>
                <!-- <el-form-item label="摘要" prop="digest">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="form.digest"/>
                </el-form-item> -->
                <el-form-item label="内容" prop="contents">
                    <!-- <div style="height: 350px" v-if="dialogVisible">
                      <div id="editor-container" style="width: 100%;height: 300px;"></div>
                    </div> v-model="form.contents"-->
                    <MyEditor v-if="dialogVisible" v-model="form.contents"></MyEditor>
                </el-form-item>
                <el-form-item label="发布人" prop="publisher">
                    <el-input v-model="form.publisher" disabled />
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <el-input v-model="form.author" />
                </el-form-item>
                <el-form-item label="来源" prop="origin">
                    <el-input v-model="form.origin" />
                </el-form-item>
                <el-form-item label="位置" prop="positions">
                    <el-checkbox-group v-model="form.positions">
                        <el-checkbox label="首页" name="positions"></el-checkbox>
                        <el-checkbox label="栏目首页" name="positions"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="发布时间" prop="releaseTime">
                    <el-input disabled v-model="form.releaseTime" />
                </el-form-item>
                <el-form-item label="是否栏目推荐" prop="columnRecommendation">
                    <el-radio-group v-model="form.columnRecommendation">
                        <el-radio label="否"></el-radio>
                        <el-radio label="是"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否开启评论" prop="enableComments">
                    <el-radio-group v-model="form.enableComments">
                        <el-radio label="否"></el-radio>
                        <el-radio label="是"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="排序号" prop="sort">
                    <el-input type="number" v-model="form.sort"></el-input>
                </el-form-item> -->
            </el-form>
            <template slot="footer">
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>
        <el-dialog width="80%" title="详情" :visible.sync="realDialog">
            <el-form label-width="120px" :model="form" class="release-details">
                <el-form-item label="分类" prop="classify">
                    <div>{{ form.classify }}</div>
                </el-form-item>
                <el-form-item label="标题" prop="titleName">
                    <div>{{ form.titleName }}</div>
                </el-form-item>
                <!-- <el-form-item label="副标题" prop="subtitle">
                    <div>{{ form.subtitle }}</div>
                </el-form-item> -->
                <el-form-item label="关键字" prop="keyWork">
                    <div>{{ form.keyWork }}</div>
                </el-form-item>
                <el-form-item label="封面" prop="coverFileName">
                    <el-image style="width: 100px;height: 100px;" :src="form.coverFileName"></el-image>
                </el-form-item>
                <!-- <el-form-item label="摘要" prop="digest">
                    <div>{{ form.digest }}</div>
                </el-form-item> -->
                <el-form-item label="内容" prop="contents">
                    <div id="real-editor-container"></div>
                </el-form-item>
                <el-form-item label="发布人" prop="publisher">
                    <div>{{ form.publisher }}</div>
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <div>{{ form.author }}</div>
                </el-form-item>
                <el-form-item label="来源" prop="origin">
                    <div>{{ form.origin }}</div>
                </el-form-item>
                <el-form-item label="位置" prop="positions">
                    <el-checkbox-group :value="form.positions">
                        <el-checkbox label="首页" name="positions"></el-checkbox>
                        <el-checkbox label="栏目首页" name="positions"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="发布时间" prop="releaseTime">
                    <div>{{ form.releaseTime }}</div>
                </el-form-item>
                <el-form-item label="是否栏目推荐" prop="columnRecommendation">
                    <el-radio-group :value="form.columnRecommendation">
                        <el-radio label="否"></el-radio>
                        <el-radio label="是"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否开启评论" prop="enableComments">
                    <el-radio-group :value="form.enableComments">
                        <el-radio label="否"></el-radio>
                        <el-radio label="是"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="排序号" prop="sort">
                    <div>{{ form.sort }}</div>
                </el-form-item> -->
            </el-form>
            <template slot="footer">
                <el-button type="primary" @click="realDialog = false">关闭</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination"
import * as ForumLecture from "../../api/ForumLecture"
import XUpload from "../../components/xupload/XUpload"
//import editorContainer from '../../components/editorContainer/editorContainer.vue'
import MyEditor from '../../components/vueUeditor.vue'
import * as classifyManger from "../../api/classifyManger";
import { handleTreeData } from "../../utils/tree";

export default {
    components: { XUpload, XPagination, MyEditor },
    data () {
        return {
            searchForm: {
                dictionaryName: "",
                dictionaryCode: "",
            },
            tableData: [],
            loading: false,
            dialogVisible: false,
            realDialog: false,
            total: 0,
            dialogTitle: "添加发布",
            form: {
                positions: []
            },
            editStatus: "add",
            formRules: {
                classify: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                titleName: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                subtitle: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                keyWork: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                coverFileName: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                digest: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                contents: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                publisher: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                // origin: [
                //     {required: true, message: '不能为空', trigger: 'blur'},
                // ],
                // positions: [
                //     {required: true, message: '不能为空', trigger: 'blur'},
                // ],
                releaseTime: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                columnRecommendation: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                enableComments: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
            },
            editor: null,

            options: [],
            props: {
                value: 'uid',
                label: 'classifyName',
                children: 'children',
                checkStrictly: true,
                emitPath: false
            },
            selectedRows: [],
            userInfo: {}
        }
    },
    methods: {
        getList (pageInfo) {
            const param = {
                ...this.searchForm,
                ...pageInfo,
                recycleType: '0'
            }
            if (param.status == '0' || param.status == '') {
                param.status = ''
            }
            ForumLecture.queryByPage(param).then(response => {
                console.log(response)
                this.tableData = response.data.data.rows
                this.total = response.data.data.total
                this.loading = false
            }).catch(error => {
                console.log(error)
            })
        },
        handleDelete (index, data) {
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true
                if (data.status === '未审核') {
                    ForumLecture.deleteById(data.uid).then(result => {
                        this.loading = false
                        this.$message.success(result.data.msg)
                        this.handleSearch()
                    }).catch(error => {
                        this.loading = false
                        console.log(error)
                    })
                } else {
                    let param = {
                        userId: this.userInfo.uid,
                        entities: [{
                            uid: data.uid,
                            recycleType: '1'
                        }]
                    }
                    classifyManger.batchDel(param).then(res => {
                        if (res.data.code == 200) {
                            this.loading = false
                            this.$message.success(res.data.msg)
                            this.handleSearch()
                        }
                    }).catch(error => {
                        this.loading = false
                        console.log(error)
                    })
                }
            }).catch(() => {
                console.log('取消删除')
            });
        },
        handleSearch () {
            this.$refs.pageInfo.loadData()
        },
        showCreateDialog () {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.getTree()
                this.getDefaltTreeNode("论坛讲座");
                this.dialogTitle = "添加发布"
                this.editStatus = "add"
                this.$refs.form.resetFields()
                this.form = Object.assign({}, this.$options.data().form)
                this.form.releaseTime = this.moment().format("YYYY-MM-DD HH:mm:ss")
                this.form.publisher = localStorage.getItem("username")
                this.form.publisherUid = localStorage.getItem("loginUid")
                this.$set(this.form, 'columnRecommendation', '否')
                this.$set(this.form, 'enableComments', '否')
            })
        },
        handleSave () {
            if (this.form.positions.includes('首页')) {
                this.form.positionsOne = '首页'
            } else {
                this.form.positionsOne = '1'
            }
            if (this.form.positions.includes('栏目首页')) {
                this.form.positionsTwo = '栏目首页'
            } else {
                this.form.positionsTwo = '1'
            }
            if (this.editStatus === "add") {
                this.handleAdd()
            } else {
                this.handleEdit()
            }
        },
        handleAdd () {
            this.$refs["form"].validate((valid) => {
                if (!valid) {
                    return false
                }
                const param = Object.assign({}, this.form)
                ForumLecture.insert(param).then(result => {
                    this.$message.success(result.data.msg)
                    this.dialogVisible = false
                    this.handleSearch()
                }).catch(error => {
                    this.$message.error(error)
                    console.log(error)
                })

            })
        },
        handleEdit () {
            this.$refs["form"].validate((valid) => {
                if (!valid) {
                    return false
                }
                const param = Object.assign({}, this.form)
                ForumLecture.update(param).then(result => {
                    this.$message.success(result.data.msg)
                    this.dialogVisible = false
                    this.handleSearch()
                }).catch(error => {
                    this.$message.error(error)
                    console.log(error)
                })
            })
        },
        showEditDialog (index, data) {
            this.dialogVisible = true
            this.$nextTick(() => {
                this.getTree()
                this.$refs['form'].resetFields()
                this.form = Object.assign({}, data)
                this.$set(this.form, 'positions', [])
                if (this.form.positionsOne == '首页') {
                    this.form.positions.push('首页')
                }
                if (this.form.positionsTwo == '栏目首页') {
                    this.form.positions.push('栏目首页')
                }
                // this.editor.txt.clear()
                // this.editor.txt.html(data.contents)
                delete this.form.createTime
                delete this.form.updateTime
                this.dialogTitle = "编辑发布"
                this.editStatus = "edit"
                if (!this.form.releaseTime) {
                    this.form.releaseTime = this.moment().format("YYYY-MM-DD HH:mm:ss")
                }
            })
        },
        handleDetails (index, data) {
            this.realDialog = true
            this.$nextTick(() => {
                this.getTree();
                this.form = Object.assign({}, data)
                this.$set(this.form, 'positions', [])
                if (this.form.positionsOne == '首页') {
                    this.form.positions.push('首页')
                }
                if (this.form.positionsTwo == '栏目首页') {
                    this.form.positions.push('栏目首页')
                }
                document.getElementById('real-editor-container').innerHTML = this.form.contents
                let video = document.getElementsByTagName('video')
                for (var i = 0; i < video.length; i++) {
                    video[i].parentElement.style.display = 'flex'
                    video[i].parentElement.style.justifyContent = 'center'
                }
            })
        },

        // 树节点
        getTree (classifyName) {
            const param = {
                classifyName
            };
            classifyManger.queryByClassifyName(param).then(response => {
                this.options = handleTreeData(response.data.data)
            }).catch(error => {
                console.log(error)
            })
        },

        getDefaltTreeNode (classifyName) {
            const param = {
                classifyName
            };
            classifyManger.queryOne(param).then(response => {
                this.form.classifyUid = response.data.data.uid
                setTimeout(() => {
                    this.$nextTick(() => {
                        this.form.classify = this.$refs.cascader.presentText;
                        console.log(this.form.classify)
                    })
                }, 1000)
            }).catch(error => {
                console.log(error)
            })
        },

        handleChange (value) {
            this.$nextTick(() => {
                this.form.classify = this.$refs.cascader.presentText;
                this.$refs.cascader.dropDownVisible = false
            })
        },
        handleSelection (selection) {
            this.selectedRows = selection;
        },
        batchDel () {
            if (this.selectedRows.length == 0) {
                this.$message.error('请勾选数据')
                return false
            }
            let entities = []
            this.selectedRows.forEach(item => {
                entities.push({
                    uid: item.uid,
                    recycleType: '1'
                })
            })
            let param = {
                userId: this.userInfo.uid,
                entities: entities
            }
            classifyManger.batchDel(param).then(response => {
                if (response.data.code == 200) {
                    this.handleSearch()
                }
            }).catch(error => {
                console.log(error)
            })
        },
        isSelectable (row, index) {
            if (row.status === '审核中') {
                return false
            } else if (row.status === '已审核') {
                if (this.userInfo.roleName === '管理员' || this.userInfo.roleName === '运营人员') {
                    return true
                } else {
                    return false
                }
            } else {
                return true
            }
        }
    },
    mounted () {
        this.userInfo = JSON.parse(localStorage.getItem('user_info'))
        this.handleSearch()
    }
}
</script>

<style scoped lang="scss">
.video-center {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
